package com.niiwoo.civet.mobile.controller.orgloan;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.mobile.util.MaskUtil;
import com.niiwoo.civet.mobile.vo.common.LinkManInfoVO;
import com.niiwoo.civet.mobile.vo.request.orgloan.LoanOrgInfoRequestVO;
import com.niiwoo.civet.mobile.vo.request.orgloan.QueryOrgLoanContractRequestVO;
import com.niiwoo.civet.mobile.vo.response.orgloan.LoanOrgInfoResponseVO;
import com.niiwoo.civet.mobile.vo.response.orgloan.OrgInfoResponseVO;
import com.niiwoo.civet.mobile.vo.response.orgloan.OrgInvestListResponseVO;
import com.niiwoo.civet.mobile.vo.response.orgloan.OrgLoanInvestContractResponseVO;
import com.niiwoo.civet.trade.dto.request.orgloan.OrgLoanInvestProjectRequestDTO;
import com.niiwoo.civet.trade.dto.response.credit.InvestUserDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.OrgInfoResponseDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.QueryOrgLoanContractReponseDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.QueryOrgLoanInvestInfoReponseDTO;
import com.niiwoo.civet.trade.service.org.OrgProjectDubboService;
import com.niiwoo.civet.trade.service.orgloan.OrgLoanDubboService;
import com.niiwoo.tripod.provider.dto.response.PageResponseDTO;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.PageRequestVO;
import com.niiwoo.tripod.web.vo.PageResponseVO;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.niiwoo.tripod.web.vo.Result.with;

/**
 * 信用借 Controller
 *
 * @author daizhiyue
 * @author weiliming
 */
@Slf4j
@RestController
@RequestMapping("/orgLoan")
@Api(tags = "机构极速借", description = "/orgLoan")
public class OrgLoanController {

    @Reference(version = "1.0.0")
    private OrgLoanDubboService orgLoanDubboService;
    @Value("${orgloan.orginvest-contract-url}")
    private String orgInvestContractUrl;
    @Reference(version = "1.0.0")
    private OrgProjectDubboService orgProjectDubboService;
    @PostMapping("/invest/orgInvestList")
    @ApiOperation("机构极速借投资记录(赖春景)")
    public Result<PageResponseVO<OrgInvestListResponseVO>> getOrgInvestmentProjectList(@RequestBody @Valid PageRequestVO pageRequestVO) {

        String userId = PrincipalContext.getUserId();
        OrgLoanInvestProjectRequestDTO requestDTO = new OrgLoanInvestProjectRequestDTO();
        requestDTO.setUserId(userId);
        requestDTO.setPageSize(pageRequestVO.getPageSize());
        requestDTO.setPageNumber(pageRequestVO.getPageNumber());
        PageResponseDTO<QueryOrgLoanInvestInfoReponseDTO> pageResponse = orgLoanDubboService.queryOrgLoanInvestInfoByProjectId(requestDTO);

        List<OrgInvestListResponseVO> resultVo = new ArrayList<>();
        PageResponseVO<OrgInvestListResponseVO> pageResponseVO = new PageResponseVO<>();
        int totalCount = pageResponse.getTotalCount();
        if (pageResponse != null) {
            List<QueryOrgLoanInvestInfoReponseDTO> orgLoanInfoReponseList = pageResponse.getItems();

            for (QueryOrgLoanInvestInfoReponseDTO orgLoanInfoReponseDTO : orgLoanInfoReponseList) {
                OrgInvestListResponseVO items = new OrgInvestListResponseVO();
                items.setProjectId(orgLoanInfoReponseDTO.getProjectId());
                items.setBorrowerUserId(orgLoanInfoReponseDTO.getBorrowerUserId());
                items.setContractAmount(orgLoanInfoReponseDTO.getBorrowAmount());
                items.setBorrowerGender(orgLoanInfoReponseDTO.getBorrowerGender());
                items.setBorrowerHeadImage(orgLoanInfoReponseDTO.getBorrowerHeadImage());
                items.setBorrowerNickName(orgLoanInfoReponseDTO.getBorrowerNickName());
                items.setBorrowRate(orgLoanInfoReponseDTO.getBorrowRate());
                items.setDeadLine(orgLoanInfoReponseDTO.getDeadLine());
                items.setDeadlineUnit(orgLoanInfoReponseDTO.getDeadlineUnit());
                items.setFullSuccessDate(orgLoanInfoReponseDTO.getFullSuccessDate());
                items.setCreateTime(orgLoanInfoReponseDTO.getCreateTime());
                if(orgLoanInfoReponseDTO.getContractUrl()==null){
                    items.setContractUrl(orgInvestContractUrl+orgLoanInfoReponseDTO.getProjectId());
                }else{
                    items.setContractUrl(orgLoanInfoReponseDTO.getContractUrl());
                }
                items.setInvestedAmount(orgLoanInfoReponseDTO.getInvestedAmount());
                items.setLoanArea(orgLoanInfoReponseDTO.getLoanArea());
                items.setRevenue(orgLoanInfoReponseDTO.getRevenue());
                items.setLoanCity(orgLoanInfoReponseDTO.getLoanCity());
                items.setStatus(orgLoanInfoReponseDTO.getStatus());
                items.setText(orgLoanInfoReponseDTO.getText());
                items.setTitle(orgLoanInfoReponseDTO.getTitle());
                resultVo.add(items);
            }
            pageResponseVO.setTotalPage(pageResponse.getTotalPage());
            pageResponseVO.setTotalCount(totalCount);
            pageResponseVO.setItems(resultVo);
        }
        return with(pageResponseVO);
    }

    @PostMapping("/showOrgLoanContract")
    @ApiOperation("提供机构极速借合同参数（赖春景）")
    public Result<OrgLoanInvestContractResponseVO> getCreditContractParms(
            @RequestBody @Valid QueryOrgLoanContractRequestVO requestVO) {

        String userId = PrincipalContext.getUserId();
        QueryOrgLoanContractReponseDTO reponseDTO = orgLoanDubboService.queryOrgLoanContractParas(requestVO.getProjectId(), userId);
        OrgLoanInvestContractResponseVO resultVo = new OrgLoanInvestContractResponseVO();
        if (reponseDTO != null) {
            resultVo.setBorrowId(reponseDTO.getBorrowId());
            resultVo.setBorrowAmount(reponseDTO.getBorrowAmount());
            resultVo.setBorrowEmail("");
            resultVo.setBorrowName(reponseDTO.getBorrowName());
            resultVo.setBorrowPlatformServiceFee(reponseDTO.getBorrowPlatformServiceFee());
            resultVo.setBorrowPlatformManageFee(reponseDTO.getBorrowPlatformManageFee());
            resultVo.setDeadline(reponseDTO.getDeadline());
            resultVo.setDeadlineUnit(reponseDTO.getDeadlineUnit());
            resultVo.setEffectiveDate(reponseDTO.getEffectiveDate());
            resultVo.setGuaranteeFee(reponseDTO.getGuaranteeFee());
            resultVo.setHorseFee(reponseDTO.getHorseFee());
            //H5端会乘以100，显示结果为0.3%
            resultVo.setPenaltyRate(new BigDecimal("0.003"));
            ////H5端没有乘以100，显示结果为0.7%
            resultVo.setRemindingServiceFee(new BigDecimal("0.7"));
            resultVo.setRefundDate(reponseDTO.getRefundDate());
            resultVo.setRepaymentType(reponseDTO.getRepaymentType());
            resultVo.setRepaymentTypeName(reponseDTO.getRepaymentTypeName());
            resultVo.setYearRate(reponseDTO.getYearRate());
            resultVo.setAddress(reponseDTO.getAddress());
            //投资人信息参数
            List<OrgLoanInvestContractResponseVO.InvestUserVO> investList = new ArrayList<OrgLoanInvestContractResponseVO.InvestUserVO>();
            List<InvestUserDTO> investInfoList = reponseDTO.getInvestUserList();
            for (InvestUserDTO investUserDTO : investInfoList) {
                OrgLoanInvestContractResponseVO.InvestUserVO investUserVO = new OrgLoanInvestContractResponseVO.InvestUserVO();
                investUserVO.setInvestId(investUserDTO.getInvestId());
                investUserVO.setInvestName(investUserDTO.getInvestName());
                investUserVO.setInvestAmount(investUserDTO.getInvestAmount());
                investList.add(investUserVO);
            }
            resultVo.setInvestUserList(investList);
        }
        return with(resultVo);

    }
    @PostMapping("/loanOrgInfo")
    @ApiOperation("查询借款企业信息(杨玉威)")
    @AuthIgnore
    public Result<LoanOrgInfoResponseVO> getLoanOrgInfoByProject(@RequestBody @Valid LoanOrgInfoRequestVO loanOrgInfoRequestVO){
        OrgInfoResponseDTO orgInfoResponseDTO = orgProjectDubboService.queryLoanOrgInfo(loanOrgInfoRequestVO.getProjectId());
        LoanOrgInfoResponseVO responseVO = new LoanOrgInfoResponseVO();
        responseVO.setOrganizationName(MaskUtil.maskCompanyName(orgInfoResponseDTO.getOrgName()));
        responseVO.setDescription(orgInfoResponseDTO.getDescription());
        responseVO.setOfficeAddress(orgInfoResponseDTO.getOfficeAddress());
        responseVO.setOperatingAge(orgInfoResponseDTO.getOperatingAge());
        responseVO.setRegisterTime(orgInfoResponseDTO.getRegisterDate());
        responseVO.setRepresentative(orgInfoResponseDTO.getRepresentative());
        responseVO.setTelephoneNumber(orgInfoResponseDTO.getTelephoneNumber());

        // 借款人联系人关系0，父亲 1，母亲 2，兄弟 3，姐妹 4，子女 5，同事 6，朋友 7，其他 8，配偶
        // 联系人关系：1配偶、2父亲、3母亲、4兄弟、5姐妹、6子女、7其他、8同事、9朋友;
        if(orgInfoResponseDTO.getLinkManInfoDTOList() != null && !orgInfoResponseDTO.getLinkManInfoDTOList().isEmpty()){
            List<LinkManInfoVO> linkManInfoVOList = new ArrayList<>();
            orgInfoResponseDTO.getLinkManInfoDTOList().forEach(link ->{
                LinkManInfoVO linkManInfoVO = new LinkManInfoVO();
                linkManInfoVO.setName(link.getName());
                linkManInfoVO.setOrderNo(link.getOrderNo());
                linkManInfoVO.setRelation(link.getRelation());
                linkManInfoVO.setMobileNo(this.maskMobile(link.getMobileNo()));
                linkManInfoVOList.add(linkManInfoVO);
            });
            responseVO.setLinkManInfoList(linkManInfoVOList);
        }

        log.info("OrgLoanController.loanOrgInfo.projectId={},responseVO={}",loanOrgInfoRequestVO.getProjectId(), JSON.toJSONString(responseVO));
        return Result.with(responseVO);
    }

    @PostMapping("/queryOrgInfo")
    @ApiOperation("查询机构信息(杨玉威)")
    @AuthIgnore
    public Result<OrgInfoResponseVO> getOrgInfoByProject(@RequestBody @Valid LoanOrgInfoRequestVO loanOrgInfoRequestVO){
        log.info("OrgLoanController.queryOrgInfo start");
        OrgInfoResponseDTO orgInfoRespDTO = orgProjectDubboService.queryOrgInfo(loanOrgInfoRequestVO.getProjectId());
        OrgInfoResponseVO responseVO = new OrgInfoResponseVO();
        responseVO.setOrganizationName(orgInfoRespDTO.getOrgName());
        responseVO.setAbbreviation(orgInfoRespDTO.getOrgShortName());
        responseVO.setDescription(orgInfoRespDTO.getDescription());
        responseVO.setProjectId(loanOrgInfoRequestVO.getProjectId());
        responseVO.setCharterUrl(orgInfoRespDTO.getCharterUrl());
        responseVO.setLogoUrl(orgInfoRespDTO.getLogoUrl());
        log.info("OrgLoanController.queryOrgInfo.projectId={},responseVO={}",loanOrgInfoRequestVO.getProjectId(), JSON.toJSONString(responseVO));
        return Result.with(responseVO);
    }

    public String maskMobile(String mobile) {
        if(!StringUtils.hasText(mobile)){
            return null;
        }
        return mobile.substring(0, 3) + "********" + mobile.substring(mobile.length(), mobile.length());
    }

}